package CSDN;

/**
 * Created with IntelliJ IDEA.
 * Description: 手写阻塞队列
 * User: 王圆豪
 * Date: 2025-05-13
 * Time: 12:53
 */
class MyBlockingQueue{
    //存储数据的数组
    private String[] data;
    //有效数据的长度
    private int sz = 0;
    //有效元素的起始索引
    private int head = 0;
    //有效数据的结束索引
    private int tail = 0;

    //构造方法，指定阻塞队列容量
    public MyBlockingQueue(int cap){
        data = new String[cap];
    }

    //存数据
    public synchronized void put(String s) throws InterruptedException {
        while (sz >= data.length) {
            this.wait();
        }
        data[tail] = s;
        tail++;
        sz++;
        if (tail >= data.length) tail  = 0;
        this.notify();
    }

    //取数据
    public synchronized String take() throws InterruptedException {
        while (sz == 0) {
             this.wait();
        }
        String tmp = data[head];
        head++;
        sz--;
        //如果索引超出范围就归零
        if (head >= data.length) head = 0;
        this.notify();
        return tmp;
    }
}

public class Test21 {
    public static void main(String[] args) {
        MyBlockingQueue intance = new MyBlockingQueue(10);
    }
}
